package com.kids.movies.fragment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.bzydroid.network.http.NetworkResponse;
import com.bzydroid.network.http.client.BzydroidHttpClient;
import com.bzydroid.network.http.exception.BzydroidNetworkExeception;
import com.bzydroid.network.http.response.HttpJSONObjectResponse;
import com.englishsong.nurseryrhymes.R;
import com.kids.movies.BaseFragment;
import com.kids.movies.E4KidsConfig;
import com.kids.movies.adapter.ItemVideoRelativeAdapter;
import com.kids.movies.customize.BaseRequestHandler;
import com.kids.movies.customize.ImageVideoDetailCustomizeList;
import com.kids.movies.entity.InfoVideo;
import com.kids.movies.service.RequestService;
import com.kids.movies.streaming.MyVideoView;
import com.kids.movies.streaming.PlayerControlWheel;
import com.kids.movies.streaming.UtilVideo;
import com.kids.movies.streaming.VideoFormat;
import com.kids.movies.streaming.VideoStream;
import com.kids.movies.util.Debug;
import com.kids.movies.util.Util;
import com.kids.movies.view.Img_List_video;
import com.nostra13.universalimageloader.core.ImageLoader;

public class IndexViewFragment extends BaseFragment  {
	private View root;
	private ListView lvVideo;
	private ItemVideoRelativeAdapter adapter;
	private int idCat;
	private LinearLayout llLoading;
	private LinearLayout llNotInternet;

	private int page = 1;

	private boolean isLoading = false;

	private TextView tvNoData;

	private RequestVideoView requestVideoView;
	private LinearLayout llLoadingFooter;
	private InfoVideo minfoVideo;
	private Bundle mBundle;
	// customvideo
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		root = inflater.inflate(R.layout.layout_list_relative_most, null);
		mBundle = savedInstanceState;

		return root;
	}


	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		lvVideo = (ListView) root.findViewById(R.id.lvRelative);
	
		tvNoData = (TextView) root.findViewById(R.id.tvNoData);

		llLoading = (LinearLayout) root.findViewById(R.id.ll_loading);
		llNotInternet = (LinearLayout) root.findViewById(R.id.llNoInternet);

		LayoutInflater inflater = getActivity().getLayoutInflater();

		View header = inflater.inflate(R.layout.layout_header, null);

		View footer = inflater.inflate(R.layout.layout_footer, null);

		llLoadingFooter = (LinearLayout) footer
				.findViewById(R.id.llLoadingFooter);

		lvVideo.addHeaderView(header);

		lvVideo.addFooterView(footer);

		adapter = new ItemVideoRelativeAdapter(getActivity(), imageLoader,
				options);

		idCat = application.getCatID();

		if (idCat == -1) {
			idCat = 0;
		}

		Debug.debug("CatId View Video : " + idCat);

		loadMore();

		lvVideo.setAdapter(adapter);

		lvVideo.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int postion = arg2 - 1;
				

			}
		});

		lvVideo.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if ((firstVisibleItem + visibleItemCount) == totalItemCount
						&& isLoading) {
					isLoading = false;
					page = page + 1;
					llLoadingFooter.setVisibility(View.VISIBLE);
					loadMore();

					Debug.debug("Page View: " + page);
				}
			}
		});
	}

	private class RequestVideoView extends BaseRequestHandler {
		public RequestVideoView(Activity context, OnClickListener clickTry) {
			super(context, clickTry);
		}

		@Override
		public void onWait(BzydroidHttpClient arg0) {
			super.onWait(arg0);
			// llLoading.setVisibility(View.VISIBLE);

		}

		@Override
		public void onStarted(BzydroidHttpClient arg0) {
			super.onStarted(arg0);
			Debug.debug("onStarted");
		}

		@Override
		public void onSuccess(BzydroidHttpClient arg0, NetworkResponse arg1) {

			// Debug.debug("Danh sach : " + a);
			HttpJSONObjectResponse jsonObjectResponse = (HttpJSONObjectResponse) arg0
					.getResponse();
			try {
				JSONObject object = jsonObjectResponse.toJSONObject();
				//
				Debug.debug("Danh sach : " + object.toString());

				JSONObject jObjData = object
						.getJSONObject(E4KidsConfig.KEY_DATA);

				int code = jObjData.getInt(E4KidsConfig.KEY_CODE);

				if (code == 1) {
					isLoading = true;

					JSONArray jArrVideo = jObjData
							.getJSONArray(E4KidsConfig.ListViewNew.KEY_VIDEO);

					int length = jArrVideo.length();

					for (int i = 0; i < length; i++) {
						JSONObject jObj = jArrVideo.getJSONObject(i);

						minfoVideo = parseJsonVideo(jObj);

						adapter.addData(minfoVideo);
					}
					
					lvVideo.setVisibility(View.VISIBLE);
				} else {

					Debug.debug("Het du lieu");
					isLoading = false;
					if (adapter.getCount() <= 0) {
						tvNoData.setVisibility(View.VISIBLE);
						lvVideo.setVisibility(View.GONE);
						llLoadingFooter.setVisibility(View.GONE);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onError(BzydroidHttpClient arg0,
				BzydroidNetworkExeception arg1) {
			super.onError(arg0, arg1);
			Debug.debug("onError");

			if (!Util.isConnectingToInternet(getActivity())) {
				lvVideo.setVisibility(View.GONE);
				if (llLoading.getVisibility() == View.VISIBLE) {
					llLoading.setVisibility(View.GONE);
					llNotInternet.setVisibility(View.VISIBLE);
				}
			} else {
				llNotInternet.setVisibility(View.GONE);
				lvVideo.setVisibility(View.VISIBLE);
			}
		}

		@Override
		public void onFinished(BzydroidHttpClient arg0) {
			super.onFinished(arg0);
			Debug.debug("onFinished");
			llLoading.setVisibility(View.GONE);
			llLoadingFooter.setVisibility(View.GONE);
		}
	}

	private void loadMore() {
		if (requestVideoView == null) {
			requestVideoView = new RequestVideoView(getActivity(), clickTry);
		}
		RequestService.rqListViewMore(idCat, String.valueOf(page), packageName,
				requestVideoView);
	}

	private OnClickListener clickTry = new OnClickListener() {

		@Override
		public void onClick(View v) {
			loadMore();
		}
	};
	// customvideo

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			lvVideo.setVisibility(View.GONE);
			getActivity().getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		} else {
			lvVideo.setVisibility(View.VISIBLE);
		}
	}
}
